#include "../process.h"
#include "../util.h"

int main(int argc, const char* argv[])
{
	fstream group(argv[1], fstream::in);
	fstream cluster(argv[2], fstream::out);
	map<string, map<string, int>> g2mem;
	map<string, map<string, int>>::iterator g2mem_itr;
	map<string, int>::iterator query2freq_itr;
	string line;
	while(!group.eof())
	{
		getline(group, line);
		int del1 = line.find("\t"), del2 = line.find("\t", del1 + 1);
		int cluster_size_s = atoi(line.substr(0, del1).c_str());

		string gid = line.substr(del1 + 1, del2 - del1 - 1);
		int cid_del = gid.find_last_of('_');
		string cid = gid.substr(0, cid_del);
		g2mem_itr = g2mem.find(cid);
		if(g2mem_itr == g2mem.end())
		{
			g2mem.insert(pair<string, map<string, int>>(cid, map<string, int>()));
			g2mem_itr = g2mem.find(cid);
		}
		map<string, int> &query2freq = (*g2mem_itr).second;
		string cluster_elem_s = line.substr(del2 + 1, line.length() - del2 - 1);
		vector<string> qf_list = util::tokenize_h(cluster_elem_s, " | ");
		for(int i = 0; i < qf_list.size(); ++ i)
		{
			string q_f = qf_list[i];
			int del = q_f.find("\t");
			string query = q_f.substr(0, del);
			string freq_c = q_f.substr(del + 1, q_f.length() - del - 1);
			int freq = atoi(freq_c.c_str());
			query2freq_itr = query2freq.find(query);
			if(query2freq_itr == query2freq.end())
				query2freq.insert(pair<string, int>(query, freq));
			else
				(*query2freq_itr).second += freq;
		}
	}
	for(g2mem_itr = g2mem.begin(); g2mem_itr != g2mem.end(); ++ g2mem_itr)
	{
		map<string, int> &query2freq = (*g2mem_itr).second;
		int size = 0;
		map<int, vector<string>> rank_list;
		map<int, vector<string>>::iterator rank_list_itr;
		for(query2freq_itr = query2freq.begin(); query2freq_itr != query2freq.end(); ++ query2freq_itr)
		{
			int freq = (*query2freq_itr).second;
			string query = (*query2freq_itr).first;
			size += freq;
			rank_list_itr = rank_list.find(-freq);
			if(rank_list_itr == rank_list.end())
			{
				vector<string> v;
				v.push_back(query);
				rank_list.insert(pair<int, vector<string>>(-freq, v));
			}
			else
				(*rank_list_itr).second.push_back(query);
		}
		if(size == 0)continue;
		cluster << size << "\t" << (*g2mem_itr).first << "\t" ;
		for(rank_list_itr = rank_list.begin(); rank_list_itr != rank_list.end(); ++ rank_list_itr)
			for(int i = 0; i < (*rank_list_itr).second.size(); ++ i)
				cluster << (*rank_list_itr).second[i] << "\t" << -(*rank_list_itr).first << " | ";
		cluster << endl;
	}
	return 0;
}